<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" size="small" :model="queryParams" class="demo-form-inline"
             v-hasPermi="['sa:delivery:query']">
      <el-form-item label="省份" prop="province">
        <el-select v-model="queryParams.province" clearable filterable placeholder="请选择省份" style="width: 100%;">
          <el-option v-for="item in provinceList" :key="item.code" :label="item.name" :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model.trim="queryParams.projectName" size="small" clearable :minlength="50"
                  placeholder="请输入项目名称"></el-input>
      </el-form-item>
      <el-form-item label="项目编号" prop="projectNo">
        <el-input v-model.trim="queryParams.projectNo" size="small" clearable :minlength="500"
                  placeholder="请输入项目编号"></el-input>
      </el-form-item>
      <el-form-item label="中标单位" prop="bidUnit">
        <el-input v-model.trim="queryParams.bidUnit" :maxlength="50" clearable placeholder="请填写中标单位名称"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['sa:delivery:add']"
                     @click="openDialog(null)">增加
          </el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table ref="tableRef" :data="tableData" v-loading="loading" highlight-current-row max-height="680"
              v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
      <el-table-column type="index" width="50" align="center" label="序号">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column property="province" label="省份" align="center" width="100"/>
      <el-table-column property="projectName" label="项目名称" align="center"/>
      <el-table-column property="projectNo" label="项目编号" align="center"/>
      <el-table-column property="orderSendDate" label="订单下发时间" align="center"/>
      <el-table-column property="orderFinishDate" label="订单完成时间" align="center"/>
      <el-table-column property="bidUnit" label="中标单位" align="center"/>
      <el-table-column property="address" label="收货地址" align="center"/>
      <el-table-column property="contactPerson" label="联系人" align="center"/>
      <el-table-column property="remark" label="备注" align="center"/>
      <el-table-column property="createBy" label="创建人" align="center" width="80"/>
      <el-table-column property="createTime" label="创建时间" align="center" sortable/>
      <el-table-column label="操作" align="center"
                       v-if="$auth.hasPermi('sa:delivery:edit') || $auth.hasPermi('sa:delivery:remove') || $auth.hasPermi('sa:delivery:view')">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-view" v-if="scope.row.attachment && $auth.hasPermi('sa:delivery:view')"
                     @click="handleView(scope.row)">查看任务单
          </el-button>
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['sa:delivery:edit']"
                     @click="openDialog(scope.row)">修改
          </el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                         @confirm="deleteHandler(scope.row)">
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['sa:delivery:remove']"
                       type="text" style="margin-left: 10px">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <el-dialog :title="dialogTitle === 1 ? '新增' : '修改'" :visible.sync="dialogVisible" width="700px"
               :close-on-click-modal="false" :fullscreen="device === 'mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" class="demo-form"
               label-position="top">
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="省份" prop="province">
              <el-select v-model="form.province" clearable filterable placeholder="请选择省份" style="width: 100%;">
                <el-option v-for="item in provinceList" :key="item.code" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目名称" prop="projectId">
              <el-input v-model="form.projectName" readonly placeholder="请选择项目" maxlength="50">
                <el-button slot="append" icon="el-icon-search" @click="handleShowProjectSelect"></el-button>
              </el-input>
              <ProjectSelect :showFlag.sync="showFlag" @onSelected="onItemSelected"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="项目编号" prop="projectNo">
              <el-input v-model="form.projectNo" readonly placeholder="项目编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="订单下发时间" prop="orderSendDate">
              <el-date-picker v-model="form.orderSendDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择订单下发时间"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="订单完成时间" prop="orderFinishDate">
              <el-date-picker v-model="form.orderFinishDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择订单完成时间"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="中标单位" prop="bidUnit">
              <el-input v-model.trim="form.bidUnit" :maxlength="50" clearable placeholder="请填写中标单位名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model.trim="form.contactPerson" :maxlength="20" clearable placeholder="请填写联系人名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="收货地址" prop="address">
              <el-input v-model.trim="form.address" :maxlength="100" clearable placeholder="请填写收货地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item>
              <div slot="label" class=" red-dot">任务单</div>
              <el-upload class="upload-demo3" ref="upload3" action="#" :limit="1" :on-change="handleTaskChange"
                         :on-remove="handleTaskRemove" :file-list="taskFileList" :auto-upload="false" accept=".pdf">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传pdf文件, 且小于20M</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :maxlength="250" placeholder="请输入备注"
                        :autosize="{ minRows: 2 }"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="uploadLoading" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/sa/task/delivery";
import ProjectSelect from "@/components/ProjectSelect/index.vue";
import {getUserProfile} from "@/api/system/user";
import {uploadImgApi} from "@/api/after/serve";
import {isFileOfType} from "@/utils"
import ProvinceData from '@/views/crm/data/province.json'
import {mapGetters} from 'vuex'

export default {
  name: 'TaskDeliveryView',
  components: {ProjectSelect},
  dicts: [],
  data() {
    return {
      env: process.env.VUE_APP_STATIC_API || '',
      // 按钮加载
      uploadLoading: false,
      // 显示项目弹窗
      showFlag: false,
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        projectId: null, // 项目ID
        id: null,
        province: "", // 省份
        projectName: "", // 项目名称
        projectNo: "", // 项目编号
        orderSendDate: "", // 订单下发时间
        orderFinishDate: "", // 订单完成时间
        bidUnit: "", // 中标单位
        address: "", // 收货地址
        contactPerson: "", // 联系人
        attachment: "", // 附件地址
        createBy: "", // 创建人
        createTime: "", // 创建时间
        remark: "", // 备注
        updateBy: "",
        updateTime: ""
      },
      // 表单的校验规则
      rules: {
        projectId: [
          {required: true, message: "请选择项目", trigger: 'change'}
        ],
        province: [
          {required: true, message: "请选择省份", trigger: 'change'}
        ],
        orderSendDate: [
          {required: true, message: "请选择订单下发时间", trigger: 'change'}
        ],
        orderFinishDate: [
          {required: true, message: "请选择订单完成时间", trigger: 'change'}
        ],
        bidUnit: [
          {required: true, message: "请填写中标单位", trigger: 'blur'}
        ],
        address: [
          {required: true, message: "请填写收货地址", trigger: 'blur'}
        ],
        contactPerson: [
          {required: true, message: "请填写联系人", trigger: 'blur'}
        ]
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        province: "",
        projectName: "",
        projectNo: "",
        bidUnit: "",
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 项目数据
      projectList: [],
      // 任务单文件
      taskFileList: [],
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ])
  },
  created() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    // this.getAllProjectList()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 查看任务单
    handleView(row) {
      window.open(this.env + row.attachment)
    },
    // 选中任务单文件
    handleTaskChange(_, fileList) {
      const maxSize = 20; // 限制最大 5MB

      const file = fileList[0] ?? null
      const fileSize = file.size / 1024 / 1024; // 转换为 MB

      if (isFileOfType(file.name, ['.pdf']) && fileSize <= maxSize) {
        this.taskFileList = fileList
      } else {
        this.$notify.error({
          title: '错误',
          message: '请检查文件类型是否为pdf, 且小于2M'
          // message: '文件不符合规范'
        });
        this.taskFileList = []
      }
    },
    // 删除任务单文件
    handleTaskRemove(_, fileList) {
      this.taskFileList = fileList
    },
    // 选中用户的回调
    onItemSelected(project) {
      this.form.projectId = project.id
      this.form.projectName = project.name
      this.form.projectNo = project.projectNo
    },
    // 显示项目选择弹窗
    handleShowProjectSelect() {
      this.showFlag = true;
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams).finally(() => {
        this.loading = false
      })
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.taskFileList = ((row.attachment ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: item
        }))
        this.form = {
          ...row
        }
        this.dialogTitle = 2
      } else {
        if (this.formId) {
          this.form = {...this.$options.data().form}
          this.taskFileList = []
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.showFlag = false
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 上传文件
    async uploadImg(fileList, cb = null) {
      if (fileList.length <= 0) {
        cb && cb("")
        return false
      }

      const urlList = (fileList ?? []).filter(i => !i.raw).map(i => i.url)

      if (urlList && urlList[0]) return false

      if (fileList.length <= 0) {
        this.form.certification = ""
        return false
      }

      const file = fileList[0]
      const formData = new FormData()
      formData.append('file', file.raw)
      const {fileName} = await uploadImgApi(formData)

      cb && cb(fileName)

      // this.form.certification = fileName ?? ""
      //
      // if(!this.form.certification) {
      //   this.fileList = []
      // }
    },
    // 导出的回调
    // async exportHandler() {
    //   this.download('crm/newspaper/export', {
    //     ...this.queryParams,
    //     userId: this.user.userId,
    //     deptId: this.user.deptId,
    //   }, `newspaper_${new Date().getTime()}.xlsx`)
    // },
    // 表单提交
    submitForm(formName) {
      if (this.taskFileList.length <= 0) {
        this.$notify({
          title: '警告',
          message: '请上传任务单',
          type: 'warning'
        });
        return false
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            this.uploadLoading = true

            // 上传任务单
            await this.uploadImg(this.taskFileList, (fileName) => {
              this.form.attachment = fileName ?? ""

              if (!this.form.attachment) {
                this.taskFileList = []
              }
            })
          } catch (error) {
            this.uploadLoading = false
          }
          this.uploadLoading = false

          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        deptId: this.user.deptId,
        userId: this.user.userId,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
        this.$refs['formRef'].resetFields();
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.resetForm('queryFormRef')
    },
    // 取消按钮
    cancel() {
      this.showFlag = false
      this.dialogVisible = false;
    },
  },
}
</script>

<style scoped lang="scss">
.oneLine {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.red-dot::before {
  content: '* ';
  color: red;
}

.cus_text {
  font-size: larger;
  margin: 10px;
}
</style>
